package com.zk.fm.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnKeyListener;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.zk.fm.R;
import com.zk.fm.entity.User;
import com.zk.fm.util.AppInfo;
import com.zk.fm.util.WebServiceUtil;

public class RegisterActivity extends Activity {
	private Button register;
	private EditText account;
	private EditText password;
	private EditText passwordCheck;
	private ProgressDialog pd;
	private long id;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		initView();
		setListener();
	}

	private void initView() {
		register = (Button) findViewById(R.id.register);
		account = (EditText) findViewById(R.id.account);
		password = (EditText) findViewById(R.id.password);
		passwordCheck = (EditText) findViewById(R.id.passwordcheck);
		pd = new ProgressDialog(this);
		pd.setMessage(getString(R.string.Registered_in));
		pd.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					id = -1;
				}
				return false;
			}
		});
	}

	private void setListener() {
		register.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				boolean validateResult = clientValidate();
				if (!validateResult) {
					return;
				}

				pd.show();
				register();
			}
		});

	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (id != msg.arg1) {
				return;
			}

			pd.dismiss();
			if (msg.what == 0) {
				// account exist
				Toast.makeText(RegisterActivity.this, R.string.accountExist, 3)
						.show();
			} else if (msg.what == 1) {
				Toast.makeText(RegisterActivity.this, R.string.registerFail, 3)
						.show();
			} else {
				Toast.makeText(RegisterActivity.this, R.string.registerSuccess,
						3).show();
				saveToPref();
				AppInfo.currentAccount = account.getText().toString().trim();
				jumpToMainPage();
				finish();
			}
		};
	};

	protected void jumpToMainPage() {
		Intent i = new Intent();
		i.setClass(RegisterActivity.this, MainActivity.class);
		startActivity(i);
	}

	protected void saveToPref() {
		SharedPreferences preferences = getSharedPreferences(
				AppInfo.xmlSavedName, PreferenceActivity.MODE_PRIVATE);
		Editor edit = preferences.edit();
		edit.putString("account", account.getText().toString().trim());
		edit.putString("password", password.getText().toString().trim());
		edit.commit();
	}

	protected void register() {
		Thread registerThread = new Thread() {
			public void run() {
				id = this.getId();
				List<Object> l = new ArrayList<Object>();
				User u = new User();
				u.setAccount(account.getText().toString().trim());
				u.setPassword(password.getText().toString().trim());
				l.add(u);
				int registerResult = 0;
				try {
					registerResult = Integer.parseInt(WebServiceUtil
							.callWebService(WebServiceUtil.METHOD_REGISTER, l,
									10000));
					System.out.println("loginResult =" + registerResult);
					mHandler.sendMessage(mHandler.obtainMessage(registerResult,
							(int) getId(), 0));

				} catch (Exception e) {
					System.out.println("e = " + e.toString());
					mHandler.sendMessage(mHandler.obtainMessage(0, (int)id, 0));
				}

			}
		};
		registerThread.start();
	}

	protected boolean clientValidate() {
		int accountLength = account.getText().length();
		int passwordLength = password.getText().length();
		int passwordCheckLength = passwordCheck.getText().length();

		if (accountLength == 0) {
			account.requestFocus();
			account.setError(getString(R.string.notnull));
			return false;
		} else {
			account.setError(null);
		}
		if (passwordLength == 0) {
			password.requestFocus();
			password.setError(getString(R.string.notnull));
			return false;
		} else {
			password.setError(null);
		}
		if (passwordCheckLength == 0) {
			passwordCheck.requestFocus();
			passwordCheck.setError(getString(R.string.notnull));
			return false;
		} else {
			passwordCheck.setError(null);
		}
		if (accountLength > 16) {
			account.requestFocus();
			account.setError(getString(R.string.accounttoolong));
			return false;
		} else {
			account.setError(null);
		}
		if (passwordLength > 32) {
			password.requestFocus();
			password.setError(getString(R.string.passwordtoolong));
			return false;
		} else {
			password.setError(null);
		}

		if (!password.getText().toString().trim()
				.equals(passwordCheck.getText().toString().trim())) {
			passwordCheck.requestFocus();
			passwordCheck.setError(getString(R.string.passwordCheckFail));
			return false;
		} else {
			passwordCheck.setError(null);
		}
		return true;
	}

}
